package adapter.notifications;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.trek2000.android.enterprise.Enterprise;
import com.trek2000.android.enterprise.R;

import java.util.ArrayList;

import controller.notifcations.AcceptInvitationToCompanyAsync;
import controller.notifcations.AcceptInvitationToCompanyGroupAsync;
import de.hdodenhof.circleimageview.CircleImageView;
import define.API;
import model.notifications.CompanyNotificationsItem;
import ui.activity.login.Login;
import ui.fragment.company.CompanyFeedFragment;
import ui.fragment.group_management.GroupManagementFragment;

/**
 * Created by trek2000 on 17/10/2014.
 */
public class CompanyNotificationsFragmentAdapter extends BaseAdapter {

    /**
     * Data section
     */
    private ArrayList <CompanyNotificationsItem> mAlCompanyNotifications = new ArrayList<>();

    /**
     * String section
     */
    private int textViewResourceId;
    private DisplayImageOptions mDio;
    private ViewHolder viewHolder;
    /**
     * The other section
     */
    private Context mContext;

    private class ViewHolder {
        private Button mBtnAccept;
        private Button mBtnDecline;
        private CircleImageView circleIvItem;
        private ImageView mIvReadOrUnread;
        private LinearLayout mLlAcceptOrDecline;
        private TextView mTvMemberName;
        private TextView mTvContent;
        private TextView mTvElapsedTime;
    }

    public CompanyNotificationsFragmentAdapter(Context context, int textViewResourceId, ArrayList<CompanyNotificationsItem> mAlcompanyNotifications) {
        this.mContext = context;
        this.textViewResourceId = textViewResourceId;
        this.mAlCompanyNotifications = mAlcompanyNotifications;

        mDio = new DisplayImageOptions.Builder()
                .delayBeforeLoading(1000)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .considerExifParams(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .build();
    }

    @Override
    public int getCount() {
        return mAlCompanyNotifications.size();
    }

    @Override
    public CompanyNotificationsItem getItem(int position) {
        return mAlCompanyNotifications.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int pos, View convertView, ViewGroup parent) {
        // Initialize variables
        if (convertView == null) {
            viewHolder = new ViewHolder();
            LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
            convertView = layoutInflater.inflate(textViewResourceId, null);

            viewHolder.mBtnAccept = (Button) convertView.findViewById(
                    R.id.btn_accept_in_simple_list_item_in_company_notifications_fragment);
            viewHolder.mBtnDecline = (Button) convertView.findViewById(
                    R.id.btn_decline_in_simple_list_item_in_company_notifications_fragment);
            viewHolder.circleIvItem = (CircleImageView) convertView.findViewById(
                    R.id.circleiv_item_in_simple_list_item_in_company_notifications_fragment);
            viewHolder.mIvReadOrUnread = (ImageView) convertView.findViewById(
                    R.id.iv_read_or_unread_in_simple_list_item_in_company_notifications_fragment);
            viewHolder.mLlAcceptOrDecline = (LinearLayout) convertView.findViewById(
                    R.id.ll_accept_or_decline_in_simple_list_item_in_company_notifications_fragment);
            viewHolder.mTvContent = (TextView) convertView.findViewById(
                    R.id.tv_content_in_simple_list_item_in_company_notifications_fragment);
            viewHolder.mTvElapsedTime = (TextView) convertView.findViewById(
                    R.id.tv_elapsed_time_in_simple_list_item_in_company_notifications_fragment);
            viewHolder.mTvMemberName = (TextView) convertView.findViewById(
                    R.id.tv_member_name_in_simple_list_item_in_company_notifications_fragment);

            viewHolder.mBtnAccept.setTag(pos);
            viewHolder.mBtnDecline.setTag(pos);
            viewHolder.circleIvItem.setTag(pos);
            viewHolder.mIvReadOrUnread.setTag(pos);
            viewHolder.mLlAcceptOrDecline.setTag(pos);
            viewHolder.mTvContent.setTag(pos);
            viewHolder.mTvElapsedTime.setTag(pos);
            viewHolder.mTvMemberName.setTag(pos);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();

            viewHolder.mBtnAccept.setTag(pos);
            viewHolder.mBtnDecline.setTag(pos);
            viewHolder.circleIvItem.setTag(pos);
            viewHolder.mIvReadOrUnread.setTag(pos);
            viewHolder.mLlAcceptOrDecline.setTag(pos);
            viewHolder.mTvContent.setTag(pos);
            viewHolder.mTvElapsedTime.setTag(pos);
            viewHolder.mTvMemberName.setTag(pos);
        }
        //set data
        if (mContext.getResources().getString(R.string.new_).equals(
                mAlCompanyNotifications.get(pos).getReadStatus())) {
            viewHolder.mIvReadOrUnread.setImageResource(R.drawable.iv_unread);
        } else {
            viewHolder.mIvReadOrUnread.setImageResource(R.drawable.iv_read);
        }
        viewHolder.mTvElapsedTime.setText(
                mAlCompanyNotifications.get(pos).getElapsedTime()
        );
        switch (mAlCompanyNotifications.get(pos).getType()) {
            case 6:
                /**
                 * Invite to company
                 * user_name,
                 * user_email,
                 * company_name,
                 * user_global_id,
                 * splash,
                 * company_id
                 */
                try {
                    String URL = "";
                    if (API.IS_DEV_SITE)
                        URL = mAlCompanyNotifications.get(pos).
                                getArgumentsOfCompanyNotifications().getSplash().replace("https", "http");
                    else
                        URL = mAlCompanyNotifications.get(pos).
                                getArgumentsOfCompanyNotifications().getSplash();

                    Enterprise.imageLoader.displayImage(
                            URL,
                            viewHolder.circleIvItem, mDio,
                            new SimpleImageLoadingListener() {
                                @Override
                                public void onLoadingStarted(String imageUri, View view) {
                                }

                                @Override
                                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {

                                }

                                @Override
                                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                                    if (loadedImage != null & view.findViewWithTag(pos) != null) {
                                        ((ImageView) view.findViewWithTag(pos)).setImageBitmap(loadedImage);
                                    }
                                }
                            }, new ImageLoadingProgressListener() {
                                @Override
                                public void onProgressUpdate(
                                        String imageUri, View view, int current, int total) {
                                }
                            });
                } catch (Exception e) {
                    e.printStackTrace();
                }
                viewHolder.mTvMemberName.setText(
                        mAlCompanyNotifications.get(pos).getArgumentsOfCompanyNotifications().getUserName()
                );
                viewHolder.mTvContent.setText(
                        Html.fromHtml("<b>" + mAlCompanyNotifications.
                                        get(pos).getArgumentsOfCompanyNotifications().getUserName() + "</b>" +
                                        " has invited you to join the company " +
                                        "<b>" + mAlCompanyNotifications.
                                        get(pos).getArgumentsOfCompanyNotifications().getCompanyName() + "</b>" +
                        " from Cloudstringers. You can join the company by clicking the link below.")
                );
                viewHolder.mLlAcceptOrDecline.setVisibility(View.VISIBLE);
                viewHolder.mBtnAccept.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //call API accept invitation to company
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                            new AcceptInvitationToCompanyAsync(mContext).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                                    String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
                                    mAlCompanyNotifications.get(pos).getArgumentsOfCompanyNotifications().getUserEmail(),
                                    String.valueOf(
                                            mAlCompanyNotifications.get(pos).getArgumentsOfCompanyNotifications().getCompanyId()));
                        else
                            new AcceptInvitationToCompanyAsync(mContext).execute(
                                    String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
                                    mAlCompanyNotifications.get(pos).getArgumentsOfCompanyNotifications().getUserEmail(),
                                    String.valueOf(
                                            mAlCompanyNotifications.get(pos).getArgumentsOfCompanyNotifications().getCompanyId()));
                    }
                });
                viewHolder.mBtnDecline.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                });
                break;
            case 20:
                /**
                 * Invite to company group
                 * user_name,
                 * company_name,
                 * user_global_id,
                 * splash,
                 * company_id
                 * group_name,
                 * group_id
                 */
                try {
                    String URL = "";
                    if (API.IS_DEV_SITE)
                        URL = mAlCompanyNotifications.get(pos).
                                getArgumentsOfCompanyNotifications().getSplash().replace("https", "http");
                    else
                        URL = mAlCompanyNotifications.get(pos).
                                getArgumentsOfCompanyNotifications().getSplash();

                    Enterprise.imageLoader.displayImage(
                            URL,
                            viewHolder.circleIvItem, mDio,
                            new SimpleImageLoadingListener() {
                                @Override
                                public void onLoadingStarted(String imageUri, View view) {
                                }

                                @Override
                                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                                }

                                @Override
                                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                                    if (loadedImage != null & view.findViewWithTag(pos) != null) {
                                        ((ImageView) view.findViewWithTag(pos)).setImageBitmap(loadedImage);
                                    }
                                }
                            }, new ImageLoadingProgressListener() {
                                @Override
                                public void onProgressUpdate(
                                        String imageUri, View view, int current, int total) {
                                }
                            });
                } catch (Exception e) {
                    e.printStackTrace();
                }
                viewHolder.mTvMemberName.setText(
                        mAlCompanyNotifications.get(pos).getArgumentsOfCompanyNotifications().getUserName()
                );
                viewHolder.mTvContent.setText(
                        Html.fromHtml("<b>" + mAlCompanyNotifications.
                                get(pos).getArgumentsOfCompanyNotifications().getUserName() + "</b>" +
                                " has invited you to join the group " +
                                "<b>" + mAlCompanyNotifications.
                                get(pos).getArgumentsOfCompanyNotifications().getGroupName() + "</b>" +
                                " in company " +
                                "<b>" + mAlCompanyNotifications.
                                get(pos).getArgumentsOfCompanyNotifications().getCompanyName() + "</b>" +
                                " from Cloudstringers. You can join the company by clicking the link below.")
                );
                viewHolder.mLlAcceptOrDecline.setVisibility(View.VISIBLE);
                viewHolder.mBtnAccept.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //call API accept invitation to company group
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                            new AcceptInvitationToCompanyGroupAsync(mContext).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                                    String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
                                    mAlCompanyNotifications.get(pos).getArgumentsOfCompanyNotifications().getUserEmail(),
                                    String.valueOf(
                                            mAlCompanyNotifications.get(pos).getArgumentsOfCompanyNotifications().getCompanyId()),
                                    String.valueOf(
                                            mAlCompanyNotifications.get(pos).getArgumentsOfCompanyNotifications().getGroupId()));
                        else
                            new AcceptInvitationToCompanyGroupAsync(mContext).execute(
                                    String.valueOf(Login.user.getUserInfo().getUserGlobalId()),
                                    mAlCompanyNotifications.get(pos).getArgumentsOfCompanyNotifications().getUserEmail(),
                                    String.valueOf(
                                            mAlCompanyNotifications.get(pos).getArgumentsOfCompanyNotifications().getCompanyId()),
                                    String.valueOf(
                                            mAlCompanyNotifications.get(pos).getArgumentsOfCompanyNotifications().getGroupId()));
                    }
                });
                viewHolder.mBtnDecline.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                });
                break;
            default:
                viewHolder.mLlAcceptOrDecline.setVisibility(View.INVISIBLE);
                break;
        }
        return convertView;
    }

    /**
     * Basic methods
     */
}
